﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WuxiWTO.Mapping;
using WutiWTO.Common;

namespace WuxiWTO.Web
{
    public partial class login : System.Web.UI.Page
    {
        WTODataContext ctx = new WTODataContext();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitTheInfo();
            }
        }

        private void InitTheInfo()
        {
            string url = Request.Url.ToString();
            if (url.IndexOf("?") > 0)
            {
                ViewState["fromHomePage"] = "N";
                ViewState["prePage"] = url.Substring(url.LastIndexOf("=") + 1, url.Length - url.LastIndexOf("=")-1);
                lblErrorMsg.Visible = true;
            }
            else
            {
                ViewState["fromHomePage"] = "Y";
                lblErrorMsg.Visible = false;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (this.txtLoginName.Text.Trim() == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "idf", "alert('请填写用户名');", true);
                return;
            }
            if (this.txtPassword.Text.Trim() == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "idf", "alert('请填写密码');", true);
                return;
            }
            var user = ctx.supporters.SingleOrDefault(p => p.supporter_login_name == this.txtLoginName.Text.Trim() && p.supporter_password == this.txtPassword.Text.Trim());
            if (user == null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "idf", "alert('用户名或者密码错误，请重新输入');", true);
                return;
            }
            else
            {
                if (chkRemember.Checked)
                {
                    HttpCookie cookie = new HttpCookie("wtouser");
                    cookie.Values["name"] = this.txtLoginName.Text.Trim();
                    cookie.Values["type"] = user.supporter_type.ToString();
                    cookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(cookie);
                }

                Session["user_name"] = this.txtLoginName.Text.Trim();
                Session["user_type"] = user.supporter_type;
                Session["user_id"] = user.supporter_id;

                if (ViewState["prePage"] != null)
                {
                    Response.Redirect(ViewState["prePage"].ToString());
                }
                else
                {
                    Response.Redirect("userCenter.aspx");
                }
            }
        }
    }
}